package transport;

import entity.RpcRequest;
import entity.RpcResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

//代理客户端发送消息 消息封装为请求
public class RpcClientProxy implements InvocationHandler {
    private static final Logger logger = LoggerFactory.getLogger(RpcClientProxy.class);
    private RpcClient client;

    public RpcClientProxy(RpcClient client) {
        this.client = client;
    }
    public RpcClientProxy() {

    }


    //根据代理类 生成被代理对象
    public <T> T getProxy(Class<T> clazz){
        return (T)Proxy.newProxyInstance(clazz.getClassLoader(),new Class<?>[]{clazz},this);
    }

    //调用代理类对象 -> 进入invoke 方法里 将一个调用封装为 一个请求
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) {
        logger.info("开始调用方法");
        logger.info("该变量的信息为：{}",method.getDeclaringClass().getName());
        RpcRequest rpcRequest = new RpcRequest(UUID.randomUUID().toString(), method.getDeclaringClass().getName(), method.getName()
                , method.getParameterTypes(), args);
        CompletableFuture<RpcResponse> completableFuture = (CompletableFuture<RpcResponse>)client.sendRequest(rpcRequest);
        //异步获取任务结果
        RpcResponse rpcResponse = null;
        try {
            rpcResponse = completableFuture.get();
            logger.info("客户端接收到消息为：{}",rpcResponse.getData());
        } catch (InterruptedException| ExecutionException e) {
            e.printStackTrace();
        }
        return rpcResponse.getData();
    }
}
